package com.wxg.ch03;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchDemo implements Runnable {
    private static final int NUM = 10;
    static final CountDownLatch end = new CountDownLatch( NUM );
    static final CountDownLatchDemo demo = new CountDownLatchDemo();
    AtomicInteger count = new AtomicInteger(1);
    @Override
    public void run() {
        try {
            // 模拟检查任务
            Thread.sleep(new Random().nextInt(10) * 1000);
            System.out.println("check complete " + count.getAndIncrement());
            end.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(NUM);
        for (int i = 0; i < NUM; i++) {
            exec.submit(demo);
        }
        // 等待检查
        end.await();
        // 发射火箭
        System.out.println("Fire!");
        exec.shutdown();
    }
}
